#include "stdafx.h"
#include "Network.h"
#include "msgproc.h"
#include "OvelLappedDescStruct.h"
#include "MsgBuf.h"
#include "Logic.h"
#include <set>
#include <MMSystem.h>

extern CNetwork* g_pNetwork;

#define WM_MY_SOCKET_MSG (WM_USER + 1000) 

ATOM				MyRegisterClass(HINSTANCE hInstance);
BOOL				InitInstance(HINSTANCE, int);
LRESULT CALLBACK	WndProc(HWND, UINT, WPARAM, LPARAM);
BOOL                InitNetwork(HWND hwnd, DWORD dwMaxConnect, DESC_BASENETWORK* pDesc);
void                ReleaseNetwork();
void				MainLoop();

int main()
{
	timeBeginPeriod(1);

	HINSTANCE hInstance = GetModuleHandle(0);

	MSG msg;

	MyRegisterClass(hInstance);

	if (!InitInstance(hInstance, SW_NORMAL))
	{
		return FALSE;
	}

	while (TRUE)	{		if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))		{			if (msg.message == WM_QUIT)				break;			TranslateMessage(&msg);			DispatchMessage(&msg);		}		else			MainLoop();	}

	timeEndPeriod(1);

	return (int) msg.wParam;
}

ATOM MyRegisterClass(HINSTANCE hInstance)
{
	WNDCLASSEX wcex;

	wcex.cbSize = sizeof(WNDCLASSEX);

	wcex.style			= CS_HREDRAW | CS_VREDRAW;
	wcex.lpfnWndProc	= WndProc;
	wcex.cbClsExtra		= 0;
	wcex.cbWndExtra		= 0;
	wcex.hInstance		= hInstance;
	wcex.hIcon			= NULL;
	wcex.hCursor		= LoadCursor(NULL, IDC_ARROW);
	wcex.hbrBackground	= (HBRUSH)(COLOR_WINDOW+1);
	wcex.lpszMenuName	= _T("");
	wcex.lpszClassName	= _T("ServerClass");
	wcex.hIconSm		= NULL;

	return RegisterClassEx(&wcex);
}

BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
	HWND hWnd;

	hWnd = CreateWindow(_T("ServerClass"), _T("Server"), WS_OVERLAPPEDWINDOW,
		CW_USEDEFAULT, 0, 640, 480, NULL, NULL, hInstance, NULL);

	if (!hWnd)
	{
		return FALSE;
	}

	DESC_BASENETWORK desc;

	desc.OnConnect = OnConnect;
	desc.OnDisconnect = OnDisconnect;
	desc.ReceivedMsg = OnReceive;
	desc.wSockEventWinMsgID = WM_MY_SOCKET_MSG;

	if (InitNetwork(hWnd, 64, &desc))
	{
		g_pNetwork->StartServer("192.168.1.133", 1001);
	}

	ShowWindow(hWnd, nCmdShow);
	UpdateWindow(hWnd);

	return TRUE;
}

LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	switch (message)
	{
	case WM_MY_SOCKET_MSG:
		SocketEventProcess();
		break;
	case WM_DESTROY:
		PostQuitMessage(0);
		ReleaseNetwork();
		break;
	default:
		return DefWindowProc(hWnd, message, wParam, lParam);
	}
	return 0;
}


BOOL InitNetwork(HWND hwnd, DWORD dwMaxConnect, DESC_BASENETWORK* pDesc)
{
	if (g_pNetwork)
		return TRUE;

	g_pNetwork = new CNetwork(hwnd, dwMaxConnect, pDesc->wSockEventWinMsgID);

	g_pNetwork->ReceivedMsg  = pDesc->ReceivedMsg;
	g_pNetwork->OnDisconnect = pDesc->OnDisconnect;
	g_pNetwork->OnConnect    = pDesc->OnConnect;

	return TRUE;
}

void ReleaseNetwork()
{
	if (g_pNetwork)
		delete g_pNetwork;

	g_pNetwork = NULL;
}